//
//  CMapViewEx.m
//  HCHK_iphone
//
//  Created by yilong zhang on 12-1-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CMapViewEx.h"

//=================================================================================================================================

@implementation MapAnnotation 
@synthesize coordinate,title,subtitle,ncolor,ntag,nIndex,bIsSelected,bIsNull; 

-(id)initWithCoordinate2D:(CLLocationCoordinate2D)coord
{
    self = [super init];
    
    if (self)
    {
        coordinate = coord;
        ncolor = 0;
        ntag   = 0;
        nIndex = 0;
        
        bIsSelected = NO;
        bIsNull = NO;
    }
    
    return  self;
}

-(void)dealloc
{ 
    [title release];
    [subtitle release];
    
    [super dealloc]; 
} 
@end

//=================================================================================================================================
@implementation MapView

/*- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    return self;
}*/

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

@end

//=================================================================================================================================

@implementation CMapViewEx

@synthesize m_Map;
@synthesize m_Pins;
@synthesize m_bIsShow;
@synthesize m_bTouchEnd;
@synthesize m_bInit;
@synthesize m_Radius;
@synthesize delegate;
@synthesize m_Placemark;
@synthesize m_nCnt;
@synthesize m_SelPin;

@synthesize m_TimerID;
@synthesize m_TimerRecord;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
        m_Placemark  = [[CAddrInfo alloc] init];
        m_bIsShow    = NO;
        m_bInit      = 0;
        m_Radius     = 1000;
        m_nCnt       = 0;
        m_TimerID    = 0;
        m_TimerRecord= 1;
        m_Pins = [[NSMutableArray array] retain];
        
        m_Map = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        //m_Map = [[MapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        m_Map.delegate = self;
        m_Map.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [m_Map setMapType:MKMapTypeStandard];
        m_Map.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake([CLocator DefaultLocator].m_Coordinate2D.latitude, [CLocator DefaultLocator].m_Coordinate2D.longitude), m_Radius, m_Radius);
        m_Map.showsUserLocation = YES;
        [self addSubview:m_Map];
        [m_Map release];
        
        UIPinchGestureRecognizer *pingesture = [[UIPinchGestureRecognizer alloc] init];
        pingesture.delegate = self;
        pingesture.delaysTouchesEnded = YES;
        [m_Map addGestureRecognizer:pingesture];
        [pingesture release];
        
        UIPanGestureRecognizer *pangesture = [[UIPanGestureRecognizer alloc] init];
        pangesture.delegate = self;
        pangesture.delaysTouchesEnded = YES;
        [m_Map addGestureRecognizer:pangesture];
        [pangesture release];
        
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DidLocationMap:) name:MSG_LOCATION_RET object:nil];
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DidLocationMap:) name:MSG_FINEME_RET object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ListenLocation:) name:MSG_LOCATION_RET object:nil];
    }
    
    return self;
}

-(void)dealloc
{
    [m_Pins release];
    [m_Placemark release];
    
    [super dealloc];
}

/*初始化地图
-(void)DidLocationMap:(NSNotification*)notification
{
    if (!m_bIsShow)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    }
    
    self.m_Placemark = notification.object;
}
 
-(void)DidReceiveFindMe:(NSNotification*)notification
{
    self.m_Placemark = notification.object;
    m_Map.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(self.m_Placemark.m_fX, self.m_Placemark.m_fY), m_Radius, m_Radius);
}
*/
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]])
    {
        m_bTouchEnd = YES;
    }
    else if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
    {
        m_bTouchEnd = YES;
    }
    else {;}

    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
}

- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
    ////NSLog(@"mapViewDidFinishLoadingMap");
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    //return;
    
    //NSLog(@"\r\n\r\nregionDidChangeAnimated\r\n\r\n");
    
    self.userInteractionEnabled = NO;
    
    if (m_bIsShow && m_bTouchEnd)
    {
        m_TimerID = [[AppConfig DefaultAppConfig] DateToInt:[[AppConfig DefaultAppConfig] GetTimeFormatString]];
        [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(DidTimerCame:) userInfo:[NSNumber numberWithLongLong:m_TimerID] repeats:NO];
    }

    MKCoordinateRegion curRegin             = m_Map.region;  
    MKMapPoint mapPointCenter               = MKMapPointForCoordinate(curRegin.center);  
    CLLocationCoordinate2D outerCoordinate  = curRegin.center;  
    outerCoordinate.latitude               += curRegin.span.latitudeDelta/2.0;  
    outerCoordinate.longitude              += curRegin.span.longitudeDelta/2.0;  
    MKMapPoint mapPointOuter                = MKMapPointForCoordinate(outerCoordinate);  
    CLLocationDistance double_distance      = MKMetersBetweenMapPoints(mapPointCenter,mapPointOuter);  
    m_Radius                                = double_distance;  
    //NSLog(@"\r\n\r\n地图半径:%f\r\n\r\n", m_Radius); 
    
    self.userInteractionEnabled = YES;
}

-(void)DidTimerCame:(NSTimer*)timer
{
    NSNumber *TimerID = timer.userInfo;
    //NSLog(@"\r\n\r\n定时器到了\r\n\r\n");
    if (m_TimerID == [TimerID longLongValue] && m_bIsShow && m_bTouchEnd)
    {
        //NSLog(@"\r\n\r\n向谷歌请求地图解析。\r\n\r\n");
        m_bTouchEnd = NO;
        m_TimerRecord = m_TimerID;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ListenLocation:) name:MSG_LOCATION_RET object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ListenLocation:) name:MSG_LOCATION_TIMEOUT object:nil];
        
        [[CLocator DefaultLocator] GetAddressInfoWithParams:zhHans Coordinate:m_Map.centerCoordinate];
        
        /*if ([self GetLocationDistance:m_Map.centerCoordinate New:m_Map.userLocation.location.coordinate] > m_Radius)
        {
            [[CLocator DefaultLocator] GetAddressInfoWithParams:zhHans Coordinate:m_Map.centerCoordinate];
        }
        else 
        {
            //NSLog(@"\r\n\r\n地图模式下，蓝色点和中心灰色点在一个范围内，以蓝色点为点位点\r\n\r\n");
            [[CLocator DefaultLocator] GetAddressInfoWithParams:zhHans Coordinate:m_Map.userLocation.location.coordinate];
        }*/
    }
}

-(void)ListenLocation:(NSNotification*)notification
{
    //NSLog(@"\r\n\r\n定时获取地图中心信息到来:%lld___%lld\r\n\r\n", m_TimerID, m_TimerRecord);
    
    //初始地图位置
    if (0 == m_bInit && !m_bIsShow)
    {
        m_bInit = 1;
        CAddrInfo *info = notification.object;
        [m_Map setCenterCoordinate:CLLocationCoordinate2DMake(info.m_fX, info.m_fY)];
    }
    //地图模式下浏览
    else if (m_TimerID == m_TimerRecord && m_bIsShow)
    {
        //NSLog(@"\r\n\r\n定时向服务器要地图中心数据:%lld____%lld\r\n\r\n", m_TimerID, m_TimerRecord);
        [self DidGetAdresss:notification.object Info:m_TimerRecord];
    }
    else {;}
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_TIMEOUT object:nil];
}
/*
-(void)DidLocationCame:(NSNotification*)notification
{
    //NSLog(@"定时获取地图中心信息到来:%lld___%lld", m_TimerID, m_TimerRecord);
    if (m_TimerID == m_TimerRecord && m_bIsShow)
    {
        //NSLog(@"定时向服务器要地图中心数据:%lld", m_TimerRecord);
        [self DidGetAdresss:notification.object Info:m_TimerRecord];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
}
*/
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKPinAnnotationView *newAnnotation = nil;
    
    if (mapView.userLocation != (MKUserLocation*)annotation && !((MapAnnotation*)annotation).bIsNull)
    {
        newAnnotation = (MKPinAnnotationView*)[m_Map dequeueReusableAnnotationViewWithIdentifier:annotation.title];
        
        if (nil == newAnnotation)
        {
            newAnnotation =  [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotation.title] autorelease]; 
            newAnnotation.animatesDrop  = YES;  
            newAnnotation.canShowCallout= YES;
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            button.tag = ((MapAnnotation*)annotation).ntag;
            [button addTarget:self action:@selector(PinTouchUpInSide:) forControlEvents:UIControlEventTouchUpInside];
            newAnnotation.rightCalloutAccessoryView = button;
        }
        
        if (((MapAnnotation*)annotation).bIsSelected)
        {
            m_SelPin = annotation;
        }
    }
    else 
    {
        [mapView.userLocation setTitle:@"我的位置"];
        [mapView.userLocation setSubtitle:@""];
    }
    
    return newAnnotation; 
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    if (m_SelPin)
    {
        [self ShowSelPin:m_SelPin];
        m_SelPin = nil;
    }
}

-(void)ShowSelPin:(MapAnnotation*)pin
{
    if (pin)
    {
        [self.m_Map selectAnnotation:pin animated:YES];
    }
}

- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView
{
    ////NSLog(@"mapViewWillStartLocatingUser");
}

- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView
{
    ////NSLog(@"mapViewDidStopLocatingUser");
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    /*if (0 == m_bInit)
    {
        if (0.000000 != m_Map.userLocation.location.coordinate.latitude && 0.000000 != m_Map.userLocation.location.coordinate.longitude)
        {
            m_Map.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(m_Map.userLocation.location.coordinate.latitude, m_Map.userLocation.location.coordinate.longitude), m_Radius, m_Radius);
            [m_Map setCenterCoordinate:m_Map.userLocation.location.coordinate animated:NO];
            
            m_bInit = 1;
        }
    }*/
}

- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    ////NSLog(@"didFailToLocateUserWithError");
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //NSLog(@"DLSKJFLDKSJF;LKSDJF;LSKDJF;LSKDJFL;SDKJF;LSKDFJDS;F");
}

-(double)GetLocationDistance:(CLLocationCoordinate2D)cur New:(CLLocationCoordinate2D)new
{
    CLLocation *l1 = [[[CLLocation alloc] initWithLatitude:new.latitude longitude:new.longitude] autorelease];
    CLLocation *l2 = [[[CLLocation alloc] initWithLatitude:cur.latitude longitude:cur.longitude] autorelease];
    
    return [l2 distanceFromLocation:l1];
}

-(void)PinTouchUpInSide:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    
    MapAnnotation *an= (MapAnnotation*)[m_Pins objectAtIndex:btn.tag];
    [delegate DidPinSelected:an.nIndex];
}

-(void)GetCurAddress:(CLLocationCoordinate2D)cur
{    
    MKReverseGeocoder *m_Geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:cur];
    m_Geocoder.delegate = self;
    [m_Geocoder start];
}

-(void)GetCurAddressEx:(NSTimer*)timer
{
    /*MKReverseGeocoder *m_Geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:m_Map.userLocation.location.coordinate];
    m_Geocoder.delegate = self;
    [m_Geocoder start];*/
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{    
    /*m_nCnt = 0;
    
    //[self DidGetAdresss:placemark];
    
    if ([geocoder retainCount] > 0)
    {
        [geocoder release];
    }*/
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    /*if (m_nCnt <= 5)
    {
        ++m_nCnt;
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GetCurAddressEx:) userInfo:geocoder repeats:NO];
    }
    else 
    {
        m_nCnt = 0;
        
        [self DidGetAdresss:nil];
    }
    
    if ([geocoder retainCount] > 0)
    {
        [geocoder release];
    }*/
}

-(void)DidGetAdresss:(CAddrInfo*)placemark Info:(long long)info
{
    self.m_Placemark = placemark;
    
    if (self.m_Placemark)
    {
        [delegate DidUpdateMapData:m_Map.centerCoordinate Radius:m_Radius State:1 Info:info];
    }
    else 
    {
        [delegate DidUpdateMapData:m_Map.centerCoordinate Radius:m_Radius State:2 Info:info];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
